<template>
  <!-- <el-drawer
    :visible.sync="drawer"
    :with-header="false"
    :size="'34%'"
  > -->
  <el-dialog
    :visible.sync="drawer"
    class="medium-common-dialog-size"
    @close="closeDialog">
    <div class="main-content">
      <!-- <div style="margin-bottom: 14px;">
        <Title title="图表预览" />
      </div> -->
      <div :style="getModuleStyle(moduleItemData)" class="card-container">
        <ChartItem
          v-if="showChart"
          ref="componentEchartRef"
          :ref-id="moduleItemData.id || 1"
          :is-data-zoom="!!chartConfig.isDataZoom"
          :chart-config="chartConfig"
          :title="moduleItemData.name"
          :rows="moduleItemData.tableData && moduleItemData.tableData.rows || []"
          :module-item-data="moduleItemData"

          :columns="moduleItemData.tableData && moduleItemData.tableData.columns || []"
          :style-config="moduleItemData.styleConfig || []"
          :show-area-max-height="300"
          :is-preview="true"
          :is-show-title="false"
        />
      </div>
    </div>
  </el-dialog>
  <!-- </el-drawer> -->
</template>

<script>
import ChartItem from '@/components/DashboardPage/items/ChartItem';
import Title from '@/components/Title';
import styleMixin from '@/views/total/dashboard/mixin/style';
export default {
  name: 'PreviewChart',
  components: { ChartItem, Title },
  mixins: [styleMixin],
  data() {
    return {
      drawer: false,
      showChart: false,
      moduleItemData: {},
      chartConfig: { moduleRadius: 4 }
    };
  },
  methods: {
    closeDialog() {
      this.drawer = false;
      setTimeout(() => {
        this.moduleItemData = {};
        this.showChart = false;
      }, 500);
    },
    open(data) {
      const result = _.cloneDeep(data);
      if (!result.dataSheet) {
        this.$message.error('请选择数据表');
        return;
      }
      if (!result.xAxis || !result.yAxis || result.yAxis.length === 0) {
        this.$message.error('请选择统计字段');
        return;
      }
      // 格式化
      if (result.styleConfig) {
        result.styleConfig = JSON.parse(result.styleConfig);
      }
      const hasContrastTime = result.contrastTime && result.contrastTime !== '';
      const hasContrastTimeRange = result.contrastTimeRange && result.contrastTimeRange.length === 2;
      if (result.chartFilter && result.yAxis && result.yAxis.length && result.chartFilter.length > 1) {
        this.handelChartFilter(result);
      }
      if (result.yAxisCombo) {
        result.yAxis.push(result.yAxisCombo);
      }
      this.mockData(result, result.type === 13 && (hasContrastTime || hasContrastTimeRange));
      if (result.type === 13 && (hasContrastTime || hasContrastTimeRange)) {
        this.handelContrast(result);
      }
      this.moduleItemData = result;
      this.showChart = true;
      this.drawer = true;
    },
    mockData(result, isContrast) {
      result.tableData = result.tableData || {};
      result.xAxis = this.getNameFromUniqueId(result.xAxis);
      result.yAxis = this.getNameFromUniqueId(result.yAxis);
      result.yAxisCombo = this.getNameFromUniqueId(result.yAxisCombo);

      const xAxis = result.xAxis;
      const yAxis = result.yAxis;
      let columns = [xAxis];
      if (yAxis) {
        if (Array.isArray(yAxis)) {
          columns = columns.concat(yAxis);
        }
      }

      if (isContrast) {
        const contrastText = (result.contrastTime && result.contrastTime !== '') ? result.contrastTime : '对比';
        [...columns].forEach(i => {
          columns.push(`${contrastText}${i}`);
        });
      }
      const dataNum = 5;
      const rows = new Array(dataNum).fill(0).map(() => new Array(columns.length));
      const timeData = this.getTimeArr(5, result.dataShowType === '按月展示');
      for (let i = 0; i < rows.length; i++) {
        for (let j = 0; j < rows[i].length; j++) {
          const isTime = columns[j] && (columns[j].indexOf('时间') >= 0 || columns[j].indexOf('日期') >= 0);
          if (j === 0) {
            rows[i][j] = !isTime ? `${xAxis}${i + 1}` : timeData[i];
          } else {
            rows[i][j] = !isTime ? this.getRandomNumberByRange(100, 1000) : this.getRandomTime(0, 0, result.dataShowType === '按月展示');
          }
        }
      }
      result.tableData.rows = rows;
      result.tableData.columns = columns;
    },
    getRandomNumberByRange(start, end) {
      return Math.floor(Math.random() * (end - start) + start);
    },
    getRandomTime(start, end, isShowMonth) {
      const nowYear = new Date().getFullYear();
      const min = start || nowYear - 10;
      const max = end || nowYear;
      const year = this.getRandomNumberByRange(min, max);
      let month = this.getRandomNumberByRange(1, 12);
      let day = null;
      if (!isShowMonth) day = this.getRandomNumberByRange(1, 30);
      if (month < 10) month = '0' + month;
      if (day && day < 10) day = '0' + day;
      return `${year}-${month}${day ? '-' + day : ''}`;
    },
    // 获取一组时间，从小到大
    getTimeArr(num, isShowMonth) {
      const time = [];
      for (let i = 0; i < num; i++) {
        time.push(this.getRandomTime(0, 0, isShowMonth));
      }
      time.sort((a, b) => {
        const aArr = a.split('-');
        const bArr = b.split('-');
        if (Number(aArr[0]) !== Number(bArr[0])) {
          return Number(aArr[0]) - Number(bArr[0]);
        } else {
          return Number(aArr[1]) - Number(bArr[1]);
        }
      });
      return time;
    },
    handelContrast(result) {
      const xAxis = result.xAxis;
      let contrastXAxisIndex = -1;
      const contrastText = (result.contrastTime && result.contrastTime !== '') ? result.contrastTime : '对比';
      const xAxisIndex = result.tableData.columns.indexOf(xAxis);
      if (result.tableData.columns && result.tableData.columns.length) {
        result.tableData.columns = result.tableData.columns.filter((i, jindex) => {
          if (i !== `${contrastText}${xAxis}`) {
            return true;
          }
          contrastXAxisIndex = jindex;
          return false;
        });
      }
      const contrastTimeArr = { YAxis: '', contrastText, items: [] };// 原时间 - 对比时间 映射表
      if (result.tableData.rows && result.tableData.rows.length) {
        result.tableData.rows.forEach(i => {
          if (i.length >= contrastXAxisIndex + 1) {
            const datatemp = i.splice(contrastXAxisIndex, 1);
            contrastTimeArr.items.push({ name: `${contrastText}${xAxis}`, time: i[xAxisIndex], contrastTime: datatemp[0] });
          }
        });
      }

      const extendYAxis = result.yAxis.map(i => {
        return `${contrastText}${i}`;
      });
      contrastTimeArr.YAxis = extendYAxis;
      result.contrastTimeArr = contrastTimeArr;
      if (extendYAxis && extendYAxis.length > 0)result.yAxis = result.yAxis.concat(extendYAxis);
    },
    handelChartFilter(result) {
      const yAxis = [];
      /**
         * 一个筛选组就会有一个数据，所以这里是为了根据筛选组同步增加 yAxis 的值，规则是 `晒选择名称-y轴名称`
         */
      for (let i = 0; i < result.yAxis.length; i++) {
        result.chartFilter.forEach(j => {
          yAxis.push(`${j.filterName}-${result.yAxis[i]}`);
        });
      }
      result.yAxis = yAxis;
    },
    getInfo(item, key) {
      return item[key];
    },
    getNameFromUniqueId(uniqueId) {
      if (!uniqueId) return uniqueId;
      if (Array.isArray(uniqueId)) {
        return uniqueId.map(i => {
          if (i.indexOf('#') < 0) return i;
          return i.split('#')[0];
        });
      }
      if (uniqueId.indexOf('#') < 0) return uniqueId;
      // uniqueId 的格式为 ${name}#${sourceId}
      return uniqueId.split('#')[0];
    }
  }
};
</script>

<style lang="scss" scoped>
.card-container {
  padding: 10px;
}
</style>
